package com.martinwj.camera2demo.utils;

import android.annotation.SuppressLint;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.widget.Toast;

import androidx.annotation.RequiresApi;

import com.martinwj.camera2demo.R;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

public class ImageUtils {

    public static List<Integer> mDatas;

    public static Context mContext;

    private static final String TAG = "ImageUtils";
//    public static Context sContext = MyApp.getInstance();

    private static final String[] STORE_IMAGES = {
            MediaStore.Images.Thumbnails._ID,
    };
    @SuppressLint("SimpleDateFormat")
    private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MMdd-HH:mm:ss");
    private static OutputStream outputStream;

    public static OutputStream insertToDB(byte[] bytes, Context sContext){
        String fileName="IMG"+"_"+DATE_FORMAT.format(new Date(System.currentTimeMillis()))+".jpg";
        String subDirection = "DCIM"+File.separator+"myCamera";
        try {
            //设置保存参数到ContentValues中
            ContentValues contentValues = new ContentValues();
            //设置文件名
            contentValues.put(MediaStore.Images.Media.DISPLAY_NAME, fileName);
            //兼容Android Q和以下版本
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                //android Q中不再使用DATA字段，而用RELATIVE_PATH代替
                //RELATIVE_PATH是相对路径不是绝对路径
                //关于系统文件夹可以到系统自带的文件管理器中查看，不可以写没存在的名字
                contentValues.put(MediaStore.Images.Media.RELATIVE_PATH, subDirection);
                //contentValues.put(MediaStore.Images.Media.RELATIVE_PATH, "Music/sample");
            } else {
                contentValues.put(MediaStore.Images.Media.DATA, Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getPath());
            }
            //设置文件类型
            contentValues.put(MediaStore.Images.Media.MIME_TYPE, "image/JPEG");
            //执行insert操作，向系统文件夹中添加文件
            //EXTERNAL_CONTENT_URI代表外部存储器，该值不变
            Uri uri = sContext.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues);
            if (uri != null) {
                //若生成了uri，则表示该文件添加成功
                //使用流将内容写入该uri中即可
                outputStream = sContext.getContentResolver().openOutputStream(uri);
                if (outputStream != null) {
                    outputStream.write(bytes);
                    outputStream.flush();
                    outputStream.close();
                }
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
        return outputStream;
    }


    public static File insertVideoToDB(Context context) {
        String fileName="IMG"+"_"+DATE_FORMAT.format(new Date(System.currentTimeMillis()))+".mp4";
        String dir = "DCIM" + File.separator + "myCamera";
        //ContentValues存放键值对
        ContentValues contentValues=new ContentValues();
        contentValues.put(MediaStore.Video.Media.DISPLAY_NAME,fileName);
        //对android API版本进行判断
        if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.Q){
            contentValues.put(MediaStore.Video.Media.RELATIVE_PATH, dir);
        }else{
            contentValues.put(MediaStore.Video.Media.DATA, Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).getPath());
        }
        //设置文件类型
        contentValues.put(MediaStore.Video.Media.MIME_TYPE,"video/mp4");
        //执行insert操作,向系统文件夹中添加文件
        Uri uri= context.getContentResolver().insert(MediaStore.Video.Media.EXTERNAL_CONTENT_URI,contentValues);
        Cursor cursor=null;
        File file=null;
        try{
            String [] strings={MediaStore.Video.Media.DATA};
            cursor=context.getContentResolver().query(uri,strings,null,null,null);
            //getColumnIndexOrThrow  --从零开始返回指定列名称,如果不存在将抛出异常
            int index=cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DATA);
            cursor.moveToFirst();//移动到第一行
            file=new File(cursor.getString(index));
            Log.i(TAG, "setUpMediaRecorder: "+cursor.getString(index));
        }finally {
            if(cursor!=null){
                cursor.close();//关闭cursor对象
            }
        }
        return file;
    }

    public static Bitmap rotateBitmap(Bitmap source, int degree, boolean flipHorizontal, boolean recycle) {
        if (degree == 0 && !flipHorizontal) {
            return source;
        }
        Matrix matrix = new Matrix();
        matrix.postRotate(degree);
        if (flipHorizontal) {
            matrix.postScale(-1, 1);
        }
        Log.d(TAG, "source width: " + source.getWidth() + ", height: " + source.getHeight());
        Log.d(TAG, "rotateBitmap: degree: " + degree);
        Bitmap rotateBitmap = Bitmap.createBitmap(source, 0, 0, source.getWidth(), source.getHeight(), matrix, false);
        Log.d(TAG, "rotate width: " + rotateBitmap.getWidth() + ", height: " + rotateBitmap.getHeight());
        if (recycle) {
            source.recycle();
        }
        return rotateBitmap;
    }

   /* @RequiresApi(api = Build.VERSION_CODES.Q)
    public static void saveImage(byte[] jpeg, Context sContext) {
        String fileName = DATE_FORMAT.format(new Date(System.currentTimeMillis())) + ".jpg";
        File outFile = new File(MediaFunc.GALLERY_PATH, fileName);
        Log.d(TAG, "saveImage. filepath: " + outFile.getAbsolutePath());
        FileOutputStream os = null;
        try {
            os = new FileOutputStream(outFile);
            os.write(jpeg);
            os.flush();
            os.close();
            insertToDB(Objects.requireNonNull(MediaFunc.getOutputMediaFile(MediaFunc.MEDIA_TYPE_IMAGE, "CAMERA")), sContext);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }*/


    /*@RequiresApi(api = Build.VERSION_CODES.Q)
    public static Uri insertToDB(File file, Context sContext) {
        if (file == null) {
            Log.e(TAG, "save image error!");
            return null;
        }
        String picturePath = file.getPath();
        // 创建contentValues对象，准备插入数据
        ContentValues values = new ContentValues();
        ContentResolver resolver = sContext.getContentResolver();
        values.put(MediaStore.Images.ImageColumns.DATA, picturePath);
        values.put(MediaStore.Images.ImageColumns.TITLE, picturePath.substring(picturePath.lastIndexOf("/") + 1));
        values.put(MediaStore.Images.ImageColumns.DATE_TAKEN, System.currentTimeMillis());
        values.put(MediaStore.Images.ImageColumns.MIME_TYPE, "image/jpeg");
        //插入数据，返回所插入数据对应的Uri
        Uri uri = resolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
        //保存之后，发送广播通知更新数据库
        sContext.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri));
        return uri;
    }*/

    /**
     *  Bitmap  位图 可以通过这个对象很方便的对图像进行操作
     * @param sContext
     * @return
     */
    public static Bitmap getLatestThumbBitmap(Context sContext) {
        Bitmap bitmap = null;
        // 按照时间顺序降序查询
        Cursor cursor = sContext.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, STORE_IMAGES, null, null, MediaStore.Files.FileColumns.DATE_MODIFIED + " DESC");
//        Cursor cursor = MediaStore.Images.Media.query(sContext.getContentResolver(), MediaStore.Images.Media
//                .EXTERNAL_CONTENT_URI, STORE_IMAGES, null, null, MediaStore.Files.FileColumns.DATE_MODIFIED + " DESC");
//        boolean first = cursor.moveToFirst();
        if (cursor.moveToFirst()) {
            long id = cursor.getLong(0);
            bitmap = MediaStore.Images.Thumbnails.getThumbnail(sContext.getContentResolver(), id, MediaStore.Images
                    .Thumbnails.MICRO_KIND, null);
            if(bitmap != null){
                Log.d(TAG, "bitmap width: " + bitmap.getWidth());
                Log.d(TAG, "bitmap height: " + bitmap.getHeight());
            }
        }
        cursor.close();
        return bitmap;
    }

    public static List<Integer> getThumbBitmapIndexs(Context sContext) {
        List<Integer> list = new ArrayList<>();
        Cursor cursor = sContext.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, STORE_IMAGES, null, null, MediaStore.Files.FileColumns.DATE_MODIFIED + " DESC");
        while (cursor.moveToNext()) {
            list.add(cursor.getInt(0));
        }
        cursor.close();
        return list;
    }

    public static Bitmap getThumbBitmap(Context sContext, long id) {
        return MediaStore.Images.Thumbnails.getThumbnail(sContext.getContentResolver(), id, MediaStore.Images
                .Thumbnails.MICRO_KIND, null);
    }
}
